package com.zx._03_并发.chapter_06_compent;

import java.util.Map;
import java.util.TreeMap;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantReadWriteLock;
import lombok.extern.slf4j.Slf4j;

/**
 * 同步组件——ReentrantReadWriteLock
 */
@Slf4j
public class Demo_05_ReentrantReadWriteLock {

    private final static Map<String, String> map = new TreeMap<>();

    private final static ReentrantReadWriteLock lock = new ReentrantReadWriteLock();

    private final static Lock readLock = lock.readLock();

    private final static Lock writeLock = lock.writeLock();

    public static String get(String key) throws Exception {
        readLock.lock();
        try {
            Thread.sleep(1000L);
            return map.get(key);
        } finally {
            readLock.unlock();
        }
    }

    public static void put(String key, String value) throws Exception {
        writeLock.lock();
        try {
            Thread.sleep(1000L);
            map.put(key, value);
        } finally {
            writeLock.unlock();
        }
    }

    public static void main(String[] args) throws Exception {
        ExecutorService executorService = Executors.newCachedThreadPool();

        executorService.execute(() -> {
            try {
                log.info("write begin");
                Demo_05_ReentrantReadWriteLock.put("kkkk", "vvvv");
                log.info("write ok");
            } catch (Exception e) {
            }
        });

        executorService.execute(() -> {
            try {
                log.info("read begin");
                log.info(Demo_05_ReentrantReadWriteLock.get("kkkk"));
                log.info("read ok");
            } catch (Exception e) {
            }
        });
    }
}
